// pages/game/game.js
import request from '../../utils/request';
import { USER_LEVELS, getUserLevel, DIFFICULTY_LEVELS } from '../../utils/constants';

Page({
  data: {
    userInfo: {},
    level: null,
    idiom: '',
    idiomLength: 4,
    imageUrl: '',
    options: [],
    selectedChars: [],
    isCorrect: false,
    isWrong: false,
    score: 0,
    usedHint: false,
    gameCompleted: false,
    showShareCard: false,
    shareImage: '',
    hintUsed: false,
    hintCost: 15,
    animation: null,
    shakingIndex: -1,
    qrcodeUrl: '/assets/images/qrcode.png', // 默认小程序码图片路径
    hasShared: false, // 是否已经分享获得过积分
    shareReward: 10,// 分享奖励积分
    honorTitles: {
      [DIFFICULTY_LEVELS.BEGINNER]: [
        "初出茅庐",
        "新手之星",
        "解谜新手",
        "逻辑萌新",
        "初级探险家"
      ],
      [DIFFICULTY_LEVELS.INTERMEDIATE]: [
        "智慧先锋",
        "解谜达人",
        "逻辑高手",
        "策略大师",
        "中级征服者"
      ],
      [DIFFICULTY_LEVELS.ADVANCED]: [
        "终极智者",
        "解谜宗师",
        "逻辑之神",
        "策略王者",
        "关卡终结者"
      ]
    },
    showLevelCompletePopup: false,
    achievementTitle: '',
    // 弹框展示的勋章🎖类型 金银铜 这里的金银铜跟等级的金银铜无关 属于勋章🎖的金银铜
    medalType: 'bronze', // 可以是 'bronze', 'silver', 'gold'
    confettiList: []
  },

  onLoad: function (options) {
    // 创建动画实例
    this.shakeAnimation = wx.createAnimation({
      duration: 100,
      timingFunction: 'ease'
    });

    // 获取用户信息
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
    }

    // 检查用户已解锁的难度
    const completedLevels = this.data.userInfo.completedLevels || [];

    
    // 处理分享进入的情况
    if (options.level_id) {
      // 直接加载指定关卡
      this.loadSpecificLevel(options.level_id);
    } else {
      // 正常难度选择进入的情况
      this.determineCurrentLevel(options.difficulty, completedLevels);
    }

    // 启用分享功能
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  determineCurrentLevel: async function (difficulty, completedLevels) {
    try {
      const levels = await this.fetchLevelData(difficulty);
      await this.handleLevelInitialization(levels, completedLevels);
    } catch (err) {
      console.error('加载关卡失败', err);
      wx.showToast({
        title: '加载关卡失败',
        icon: 'none'
      });
    }
  },

  // 新增：获取关卡数据
  fetchLevelData: async function(difficulty) {
    const res = await request({
      url: '/level',
      method: 'GET',
      data: { difficulty }
    });

    if (!res.data || !res.data.list) {
      throw new Error('获取关卡数据失败');
    }

    return this.sortLevelsByOrder(res.data.list);
  },

  // 新增：统一的关卡排序函数
  sortLevelsByOrder: function(levels) {
    return levels.sort((a, b) => parseInt(a.order) - parseInt(b.order));
  },

  // 新增：处理关卡初始化逻辑
  handleLevelInitialization: async function(levels, completedLevels) {
    const uncompletedLevels = levels.filter(level => !completedLevels.includes(level.id));

    if (uncompletedLevels.length > 0) {
      // 初始化第一个未完成的关卡
      this.initializeGame(uncompletedLevels[0]);
    } else if (completedLevels.length > 0) {
      // 如果该难度全部完成,显示最后一关
      const lastLevel = levels[levels.length - 1];
      this.initializeGame(lastLevel);
      this.setData({
        selectedChars: lastLevel.idiom.split('')
      });
      this.showHonorCard(this.data.userInfo.name || '玩家');
    } else {
      wx.showToast({
        title: '暂无关卡',
        icon: 'none'
      });
    }
  },

  loadLevel: async function (difficulty) {
    try {
      const levels = await this.fetchLevelData(difficulty);
      const completedLevels = this.data.userInfo.completedLevels || [];
      await this.handleLevelInitialization(levels, completedLevels);
    } catch (err) {
      console.error('加载关卡失败', err);
      wx.showToast({
        title: '加载关卡失败',
        icon: 'none'
      });
    }
  },

  getRandomHonorTitle: function (difficulty) {
    const titles = this.data.honorTitles[difficulty] || this.data.honorTitles[DIFFICULTY_LEVELS.BEGINNER];
    const randomIndex = Math.floor(Math.random() * titles.length);
    return titles[randomIndex];
  },
  drawHonorCard: function (canvasId, title, playerName) {
    const ctx = wx.createCanvasContext(canvasId);

    // 设置卡片背景
    ctx.setFillStyle("#FFFFFF");
    ctx.fillRect(0, 0, 300, 400);

    // 绘制边框
    ctx.setStrokeStyle("#FFD700");
    ctx.strokeRect(5, 5, 290, 390);

    // 绘制标题
    ctx.setFontSize(24);
    ctx.setFillStyle("#333333");
    ctx.setTextAlign('center');
    ctx.fillText("荣誉成就", 150, 50);

    // 绘制荣誉称号
    ctx.setFontSize(36);
    ctx.setFillStyle("#FF4500");
    ctx.fillText(title, 150, 150);

    // 绘制玩家名称
    ctx.setFontSize(20);
    ctx.setFillStyle("#000000");
    ctx.fillText(`玩家: ${playerName}`, 150, 200);

    // 绘制完成时间
    const date = new Date().toLocaleDateString();
    ctx.setFontSize(16);
    ctx.setFillStyle("#000000");
    ctx.fillText(`完成时间: ${date}`, 150, 250);

    // 加载并绘制小程序码
    wx.getImageInfo({
      src: this.data.qrcodeUrl,
      success: (qrcodeImage) => {
        ctx.drawImage(qrcodeImage.path, 110, 270, 80, 80);

        // 绘制完成后生成图片
        ctx.draw(false, () => {
          wx.canvasToTempFilePath({
            canvasId,
            success: (res) => {
              this.setData({
                shareImage: res.tempFilePath
              });
            },
            fail: (err) => {
              console.error('生成贺卡图片失败', err);
            }
          });
        });
      },
      fail: (err) => {
        console.error('获取小程序码失败', err);
      }
    });
  },
  // 显示名誉卡片
  showHonorCard: function (playerName) {
    const difficulty = this.data.level ? this.data.level.difficulty : DIFFICULTY_LEVELS.BEGINNER;
    const title = this.getRandomHonorTitle(difficulty);
    
    let medalType = 'bronze';
    if(difficulty === DIFFICULTY_LEVELS.INTERMEDIATE) {
      medalType = 'silver';
    } else if(difficulty === DIFFICULTY_LEVELS.ADVANCED) {
      medalType = 'gold';
    }

    // 生成雪花数据
    const confettiList = this.generateConfetti();

    this.setData({
      showLevelCompletePopup: true,
      achievementTitle: title,
      medalType: medalType,
      confettiList: confettiList
    });

    // 播放成就音效
    // const achievementAudio = wx.createInnerAudioContext();
    // achievementAudio.src = '/assets/audio/achievement.mp3';
    // achievementAudio.play();
  },

  // 生成雪花数据
  generateConfetti: function() {
    const confettiList = [];
    const colors = ['#ffffff', '#E6E6FA', '#F0F8FF'];
    
    for(let i = 0; i < 30; i++) {
      confettiList.push({
        left: Math.random() * 100, // 随机左边距
        delay: Math.random() * 3, // 随机延迟
        size: Math.random() * 10 + 5, // 随机大小
        color: colors[Math.floor(Math.random() * colors.length)] // 随机颜色
      });
    }
    
    return confettiList;
  },

  // 初始化游戏
  initializeGame: function (level) {
    if (!level) return;
    
    const cleanOptions = this.getCleanOptions(level.options);
    
    this.setData({
      level: {
        ...level,
        order: level.order || 1  // 确保有关卡序号
      },
      idiom: level.idiom,
      idiomLength: level.idiom.length,
      imageUrl: level.imageUrl,
      options: this.shuffleArray(cleanOptions),
      selectedChars: new Array(level.idiom.length).fill(''),
      isCorrect: false,
      isWrong: false,
      score: level.score || 10,
      usedHint: false,
      gameCompleted: false,
      hintUsed: false,
      hasShared: false
    });
  },

  // 新增：处理选项清理的逻辑
  getCleanOptions: function(options) {
    try {
      const parsedOptions = typeof options === 'string' ? JSON.parse(options) : options;
      return parsedOptions.filter(char => /^[\u4e00-\u9fa5]$/.test(char));
    } catch (err) {
      console.error('选项解析失败', err);
      return [];
    }
  },

  // 打乱数组顺序
  shuffleArray: function (array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 选择字符
  selectChar: function (e) {
    if (this.data.gameCompleted) return;

    const index = e.currentTarget.dataset.index;
    const char = this.data.options[index];

    // 查找第一个空位
    const selectedChars = [...this.data.selectedChars];
    const emptyIndex = selectedChars.findIndex(item => item === '');

    if (emptyIndex !== -1) {
      selectedChars[emptyIndex] = char;

      this.setData({
        selectedChars
      });

      // 检查是否填满了所有空格
      if (selectedChars.every(item => item !== '')) {
        this.checkAnswer();
      }
    }
  },

  // 移除已选择的字符
  removeChar: function (e) {
    if (this.data.gameCompleted) return;

    const index = e.currentTarget.dataset.index;
    const selectedChars = [...this.data.selectedChars];

    if (selectedChars[index] !== '') {
      selectedChars[index] = '';

      this.setData({
        selectedChars,
        isWrong: false
      });
    }
  },

  // 检查答案
  checkAnswer: function () {
    const userAnswer = this.data.selectedChars.join('');
    const correctAnswer = this.data.idiom;

    if (userAnswer === correctAnswer) {
      // 答案正确
      this.setData({
        isCorrect: true,
        gameCompleted: true
      });

      // 播放正确音效
      const correctAudio = wx.createInnerAudioContext();
      correctAudio.src = '/assets/audio/correct.mp3';
      correctAudio.play();

      // 更新用户积分和已完成关卡
      this.updateUserProgress();

      // 显示成功提示
    } else {
      // 答案错误
      this.setData({
        isWrong: true
      });

      // 播放错误音效
      const wrongAudio = wx.createInnerAudioContext();
      wrongAudio.src = '/assets/audio/wrong.mp3';
      wrongAudio.play();

      // 执行抖动动画
      this.shakeAnswerBoxes();
    }
  },

  // 抖动答案框
  shakeAnswerBoxes: function () {
    const animation = wx.createAnimation({
      duration: 50,
      timingFunction: 'linear'
    });

    animation.translateX(5).step();
    animation.translateX(-10).step();
    animation.translateX(10).step();
    animation.translateX(-5).step();
    animation.translateX(0).step();

    this.setData({
      animation: animation.export()
    });
  },

  // 使用提示
  useHint: function () {
    if (this.data.gameCompleted || this.data.hintUsed) return;

    const userScore = this.data.userInfo.score || 0;
    const hintCost = this.data.hintCost;

    if (userScore < hintCost) {
      wx.showToast({
        title: `积分不足，需要${hintCost}积分`,
        icon: 'none'
      });
      return;
    }

    // 找到第一个空位
    const selectedChars = [...this.data.selectedChars];
    const emptyIndex = selectedChars.findIndex(item => item === '');

    if (emptyIndex !== -1) {
      // 填入正确的字符
      selectedChars[emptyIndex] = this.data.idiom[emptyIndex];

      // 更新用户积分
      const app = getApp();
      
      request({
        url: '/deductScore',
        method: 'POST',
        data: {
          openId: this.data.userInfo.openId,
          score: hintCost,
          levelId: this.data.level.id
        }
      }).then(() => {
        // 更新全局用户信息
        app.globalData.userInfo.score -= hintCost;

        this.setData({
          selectedChars,
          hintUsed: true,
          userInfo: app.globalData.userInfo
        });

        // 检查是否填满了所有空格
        if (selectedChars.every(item => item !== '')) {
          this.checkAnswer();
        }
      }).catch(err => {
        console.error('更新积分失败', err);
        wx.showToast({
          title: '更新积分失败',
          icon: 'none'
        });
      });
    } else {
      wx.showToast({
        title: '已填满所有空格',
        icon: 'none'
      });
    }
  },

  // 更新用户进度
  updateUserProgress: async function () {
    try {
      const levelId = this.data.level.id;  // 注意这里使用 id 而不是 _id
      const earnedScore = this.data.hintUsed ? Math.floor(this.data.score / 2) : this.data.score;
      const app = getApp();

      if (this.data.userInfo.completedLevels && this.data.userInfo.completedLevels.includes(levelId)) {
        return;
      }


      const completedLevels = this.data.userInfo.completedLevels || [];
      completedLevels.push(levelId);

      // 更新用户进度和积分
      // 这里需要替换为你的实际 API
      const response = await request({
        url: '/updateLevelAndScore',
        method: 'POST',
        data: {
          openId: this.data.userInfo.openId,
          levelId: levelId,
          score: earnedScore, // 返回的是全部的积分
        }
      });

      if (response.code === 0) {
        // 更新全局用户信息
        app.globalData.userInfo.score += earnedScore;
        app.globalData.userInfo.completedLevels = completedLevels;

        this.setData({
          userInfo: app.globalData.userInfo
        });

        this.checkUnlockNextDifficulty();
        // this.checkLevelUp();
      } else {
        throw new Error(response.msg || '更新进度失败');
      }
    } catch (err) {
      console.error('更新用户进度失败', err);
      wx.showToast({
        title: '更新进度失败',
        icon: 'none'
      });
    }
  },

  // 检查是否需要解锁下一个难度
  checkUnlockNextDifficulty: async function () {
    try {
      const currentDifficulty = this.data.level.difficulty;
      const nextDifficulty = this.getNextDifficulty(currentDifficulty);
      
      if (!nextDifficulty) return;

      const levels = await this.fetchLevelData(currentDifficulty);
      const allLevelIds = levels.map(level => level.id);
      const completedLevels = this.data.userInfo.completedLevels || [];

      // 确保只在所有关卡完成时解锁下一个难度
      const allCompleted = allLevelIds.every(id => completedLevels.includes(id));

      if (allCompleted) {
        await this.unlockNextDifficulty(nextDifficulty);
      }
    } catch (err) {
      this.handleError('解锁难度失败', err);
    }
  },

  // 新增：解锁下一难度的逻辑
  unlockNextDifficulty: async function(nextDifficulty) {
    const app = getApp();
    const response = await request({
      url: '/updateLevelAndScore',
      method: 'POST',
      data: {
        openId: this.data.userInfo.openId,
        difficulty: nextDifficulty
      }
    });

    if (response.code === 0) {
      app.globalData.userInfo.unlockedDifficulty = nextDifficulty;
      
      this.setData({
        userInfo: app.globalData.userInfo
      });

      wx.showToast({
        title: `已解锁${nextDifficulty}难度！`,
        icon: 'none',
        duration: 2000
      });
    } else {
      throw new Error(response.msg || '更新难度失败');
    }
  },

  // 获取下一个难度
  getNextDifficulty: function (currentDifficulty) {
    switch (currentDifficulty) {
      case DIFFICULTY_LEVELS.BEGINNER:
        return DIFFICULTY_LEVELS.INTERMEDIATE;
      case DIFFICULTY_LEVELS.INTERMEDIATE:
        return DIFFICULTY_LEVELS.ADVANCED;
      default:
        return null;
    }
  },

  // 下一关
  nextLevel: async function () {
    try {
      const currentDifficulty = this.data.level.difficulty;
      const currentOrder = this.data.level.order;
      
      // 复用 fetchLevelData 函数获取关卡数据
      const levels = await this.fetchLevelData(currentDifficulty);
      const completedLevels = this.data.userInfo.completedLevels || [];

      // 找到当前关卡之后的第一个未完成关卡
      const nextLevel = levels.find(level => 
        parseInt(level.order) > currentOrder && 
        !completedLevels.includes(level.id)
      );

      if (nextLevel) {
        this.initializeGame(nextLevel);
      } else {
        this.setData({ gameCompleted: false });
        this.showHonorCard(this.data.userInfo.name || '玩家');
        // this.handleLevelCompletion();

      }
    } catch (err) {
      this.handleError('加载下一关失败', err);
    }
  },

  // 新增：处理难度完成的逻辑
  handleLevelCompletion: function() {
    wx.showModal({
      title: '提示',
      content: '当前难度的关卡已全部完成！',
      showCancel: true,
      success: () => {
        wx.navigateBack();
      }
    });
  },

  // 返回难度选择页面或首页
  backToLevelSelect: function () {
    const pages = getCurrentPages();
    if (pages.length > 1) {
      // 如果有路由栈，正常返回上一页
      wx.navigateBack();
    } else {
      // 如果没有路由栈，跳转到首页
      wx.reLaunch({
        url: '/pages/index/index'
      });
    }
  },

  // 分享给好友
  shareToFriend: function () {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage']
    });
  },

  // 保存分享图片到相册
  saveShareImage: function () {
    wx.showLoading({
      title: '生成图片中...',
    });

    // 创建临时图片
    this.generateShareImage(() => {
      wx.hideLoading();

      wx.saveImageToPhotosAlbum({
        filePath: this.data.shareImage,
        success: () => {
          wx.showToast({
            title: '图片已保存到相册',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('保存图片失败', err);
          if (err.errMsg.indexOf('auth deny') >= 0) {
            wx.showModal({
              title: '提示',
              content: '需要您授权保存相册',
              showCancel: false,
              success: () => {
                wx.openSetting({
                  success(res) {
                    console.log('设置结果', res);
                  }
                });
              }
            });
          } else {
            wx.showToast({
              title: '保存失败，请重试',
              icon: 'none'
            });
          }
        }
      });
    });
  },

  // 生成分享图片
  generateShareImage: function (callback) {
    const ctx = wx.createCanvasContext('shareCanvas');
    const canvasWidth = 375;
    const canvasHeight = 550;
    const themeColor = '#818CF8'; // 您的主题色
    const secondaryColor = '#F0F1FE'; // 主题色的淡色版作为背景

    // 整体背景 - 使用主题色的超淡色调
    ctx.setFillStyle(secondaryColor);
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);

    // 添加顶部彩色边框 - 使用主题色
    ctx.setFillStyle(themeColor);
    ctx.fillRect(0, 0, canvasWidth, 15);

    // 绘制标题 - 使用主题色
    ctx.setFillStyle(themeColor);
    ctx.setFontSize(28);
    ctx.setTextAlign('center');
    ctx.fillText('看图猜成语', canvasWidth / 2, 55);

    // 绘制副标题
    ctx.setFillStyle('#555555');
    ctx.setFontSize(14);
    ctx.fillText('提升文化素养的益智游戏', canvasWidth / 2, 80);

    // 绘制卡通风格的图片框
    // 外框背景
    ctx.setFillStyle('#FFFFFF');
    ctx.fillRect(35, 95, 305, 235);

    // 边框装饰 - 使用主题色
    ctx.beginPath();
    ctx.setStrokeStyle(themeColor);
    ctx.setLineWidth(3);

    // 简单的点状虚线边框
    for (let i = 0; i < 305; i += 10) {
      ctx.moveTo(35 + i, 95);
      ctx.lineTo(35 + i + 5, 95);

      ctx.moveTo(35 + i, 330);
      ctx.lineTo(35 + i + 5, 330);
    }

    for (let i = 0; i < 235; i += 10) {
      ctx.moveTo(35, 95 + i);
      ctx.lineTo(35, 95 + i + 5);

      ctx.moveTo(340, 95 + i);
      ctx.lineTo(340, 95 + i + 5);
    }
    ctx.stroke();

    // 加载成语图片
    wx.getImageInfo({
      src: this.data.imageUrl,
      success: (idiomImage) => {
        // 绘制图像内容
        ctx.drawImage(idiomImage.path, 45, 105, 285, 215);

        // 创建卡通风格的文本区域
        ctx.setFillStyle('#FFFFFF');
        ctx.fillRect(35, 350, 305, 90);

        // 气泡装饰边框
        ctx.beginPath();
        ctx.setStrokeStyle(themeColor);
        ctx.setLineWidth(3);
        ctx.strokeRect(35, 350, 305, 90);

        // 添加圆角装饰点
        ctx.setFillStyle(themeColor);
        ctx.beginPath();
        ctx.arc(35, 350, 6, 0, 2 * Math.PI);
        ctx.fill();

        ctx.beginPath();
        ctx.arc(340, 350, 6, 0, 2 * Math.PI);
        ctx.fill();

        ctx.beginPath();
        ctx.arc(35, 440, 6, 0, 2 * Math.PI);
        ctx.fill();

        ctx.beginPath();
        ctx.arc(340, 440, 6, 0, 2 * Math.PI);
        ctx.fill();

        // 绘制提示文字 - 使用主题色
        ctx.setFillStyle(themeColor);
        ctx.setFontSize(18);
        ctx.setTextAlign('center');
        ctx.fillText('扫码进入小程序', canvasWidth / 2, 380);

        ctx.setFillStyle('#555555');
        ctx.setFontSize(16);
        ctx.fillText('帮我猜猜这是什么成语', canvasWidth / 2, 410);

        // 绘制小程序码
        wx.getImageInfo({
          src:'/assets/imagesqrcode.png',
          success: (qrcodeImage) => {
            // 绘制一个卡通风格的圆形框
            ctx.setFillStyle('#FFFFFF');
            ctx.beginPath();
            ctx.arc(canvasWidth / 2, 490, 60, 0, 2 * Math.PI);
            ctx.fill();

            ctx.setStrokeStyle(themeColor);
            ctx.setLineWidth(3);
            ctx.beginPath();
            ctx.arc(canvasWidth / 2, 490, 60, 0, 2 * Math.PI);
            ctx.stroke();

            // 绘制小程序码
            ctx.drawImage(qrcodeImage.path, canvasWidth / 2 - 50, 440, 100, 100);

            // 完成绘制
            ctx.draw(false, () => {
              setTimeout(() => {
                wx.canvasToTempFilePath({
                  canvasId: 'shareCanvas',
                  success: res => {
                    this.setData({
                      shareImage: res.tempFilePath
                    });
                    if (callback) callback();
                  },
                  fail: (err) => {
                    console.error('生成图片失败', err);
                    wx.showToast({
                      title: '生成图片失败',
                      icon: 'none'
                    });
                  }
                });
              }, 300);
            });
          },
          fail: (err) => {
            console.error('获取小程序码失败', err);
            ctx.draw(false, () => {
              setTimeout(() => {
                wx.canvasToTempFilePath({
                  canvasId: 'shareCanvas',
                  success: res => {
                    this.setData({
                      shareImage: res.tempFilePath
                    });
                    if (callback) callback();
                  },
                  fail: (err) => {
                    console.error('生成图片失败', err);
                    wx.showToast({
                      title: '生成图片失败',
                      icon: 'none'
                    });
                  }
                });
              }, 300);
            });
          }
        });
      },
      fail: (err) => {
        console.error('加载图片资源失败', err);
        wx.showToast({
          title: '生成图片失败',
          icon: 'none'
        });
      }
    });
  },

  // 关闭分享卡片
  closeShareCard: function () {
    this.setData({
      showShareCard: false
    });
  },

  // 防止滑动穿透
  preventTouchMove: function () {
    return false;
  },

  // 分享给好友（小程序原生分享）
  onShareAppMessage: function () {
    // 如果用户还没有获得分享奖励，则给予奖励
    if (!this.data.hasShared) {
      this.addShareReward();
    }

    return {
      title: '快来帮我猜猜这是什么成语!',
      path: `/pages/game/game?level_id=${this.data.level.id}`,
      imageUrl: this.data.imageUrl, // 可选：使用当前关卡的图片作为分享图片
    };
  },

  // 添加分享奖励
  addShareReward: async function () {
    try {
      const app = getApp();
      
      await request({
        url: '/updateLevelAndScore',
        method: 'POST',
        data: {
          openId: this.data.userInfo.openId,
          score: this.data.shareReward
        }
      });

      app.globalData.userInfo.score += this.data.shareReward;

      this.setData({
        userInfo: app.globalData.userInfo,
        hasShared: true
      });

      wx.showToast({
        title: `分享成功，获得${this.data.shareReward}积分`,
        icon: 'none',
        duration: 2000
      });

      // this.checkLevelUp();
    } catch (err) {
      console.error('添加分享奖励失败', err);
    }
  },


  handleShareAchievement() {
    wx.shareAppMessage({
      title: `我获得了"${this.data.achievementTitle}"称号！`,
      path: '/pages/index/index',
      imageUrl: this.data.imageUrl // 使用当前关卡的图片
    });
  },

  handleClosePopup() {
    this.setData({ showLevelCompletePopup: false });
  },

  // 新增：加载指定关卡
  loadSpecificLevel: async function(levelId) {
    try {
      const res = await request({
        url: '/level/detail',
        method: 'GET',
        data: { levelId }
      });
      

      if (!res.data || !res.data.level) {
        throw new Error('获取关卡数据失败');
      }

      this.initializeGame(res.data.level);
    } catch (err) {
      this.handleError('加载指定关卡失败', err);
    }
  },

  handleSaveAchievement: function() {
    this.setData({
      showLevelCompletePopup: false
    });
    // 返回到首页
    wx.navigateBack();
  },

  // 新增：统一的错误处理函数
  handleError: function(message, error) {
    console.error(message, error);
    wx.showToast({
      title: message,
      icon: 'none'
    });
  },
});